package www.tshu.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class TuShuUtil {
    private static DataSource dataSource;
    private static ThreadLocal<Connection>threadLocal =new ThreadLocal<>();
    static {
        try {
            InputStream inputStream = TuShuUtil.class.getClassLoader().getResourceAsStream("tushu.properties");
            Properties pro = new Properties();
            pro.load(inputStream);
            dataSource = DruidDataSourceFactory.createDataSource(pro);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    public static Connection getConnection(){
        Connection conn = threadLocal.get();
        try {
            if(conn==null||conn.isClosed()){
                conn= dataSource.getConnection();
                threadLocal.set(conn);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return conn;
    }
    public static void close(){
        Connection conn = threadLocal.get();
        try {
            if (conn!=null&&!conn.isClosed()){
                conn.close();
                threadLocal.set(null);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
